package cn.caplike.demo.nio._2021.buffer;

import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;

/**
 * Description: 文件锁.
 *
 * @author LiKe
 * @version 1.0.0
 * @date 2022-01-18 12:38
 */
public class FileLockDemo {

    public static void main(String[] args) throws Exception {
        final String path = FileLockDemo.class.getResource("/data/file-lock-demo.txt").getPath();
        System.out.println("path: " + path);
        RandomAccessFile randomAccessFile = new RandomAccessFile(path, "rw");
        FileChannel fileChannel = randomAccessFile.getChannel();

        FileLock fileLock = fileChannel.lock(3, 6, true);

        System.out.println("valid: " + fileLock.isValid());
        System.out.println("lock type: "  + fileLock.isShared()); // 共享锁

        fileLock.release();
        randomAccessFile.close();
    }
}
